package com.example.taphelper

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.example.taphelper.service.TapAccessibilityService
import com.example.taphelper.utils.TapConfig

class FullScreenImageActivity : AppCompatActivity() {
    
    companion object {
        private const val TAG = "FullScreenImageActivity"
        const val EXTRA_IMAGE_URI = "image_uri"
        const val RESULT_CLICK_POSITION = "click_position"
        const val RESULT_SPACE_TIME = "space_time"
        const val RESULT_DELAY_TIME = "delay_time"
    }
    
    private lateinit var imageView: ImageView
    private lateinit var topBar: LinearLayout
    private lateinit var btnClose: Button
    private lateinit var btnMode: Button
    private lateinit var crosshairVertical: View
    private lateinit var crosshairHorizontal: View
    private lateinit var clickMarker: View
    private lateinit var overlayView: View
    
    // 选择模式
    private var isRectangleMode = false
    
    // 单点选择相关
    private var clickX: Int = 0
    private var clickY: Int = 0
    private var isDragging = false
    private var hasSelected = false
    
    // 矩形选择相关
    private var rectangleStartX = 0f
    private var rectangleStartY = 0f
    private var rectangleEndX = 0f
    private var rectangleEndY = 0f
    private var isSelectingRectangle = false
    private var hasSelectedRectangle = false
    private var isEditingRectangle = false
    private var editingHandle = EditHandle.NONE
    private var lastTouchX = 0f
    private var lastTouchY = 0f
    
    // 矩形编辑控制按钮
    private var btnConfirmRect: Button? = null
    private var btnCancelRect: Button? = null
    private var editButtonsContainer: LinearLayout? = null
    
    // 矩形编辑手柄类型
    enum class EditHandle {
        NONE,
        TOP_LEFT,
        TOP_RIGHT,
        BOTTOM_LEFT,
        BOTTOM_RIGHT,
        LEFT_EDGE,
        RIGHT_EDGE,
        TOP_EDGE,
        BOTTOM_EDGE,
        MOVE_RECT
    }
    
    // 自定义覆盖视图用于绘制矩形
    private lateinit var drawingOverlay: DrawingOverlay
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置全屏显示
        setupFullScreen()
        
        setContentView(R.layout.activity_fullscreen_image)
        
        initViews()
        setupListeners()
        loadImage()
        
        // 确保在布局完成后再次设置全屏
        window.decorView.post {
            hideSystemUI()
        }
    }
    
    override fun onResume() {
        super.onResume()
        hideSystemUI()
    }
    
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            hideSystemUI()
        }
    }
    
    private fun setupFullScreen() {
        // 隐藏ActionBar
        supportActionBar?.hide()
        
        // 设置窗口标志
        window.apply {
            setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
            
            // 设置状态栏和导航栏透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                statusBarColor = android.graphics.Color.TRANSPARENT
                navigationBarColor = android.graphics.Color.TRANSPARENT
            }
        }
        
        // 使用WindowCompat设置全屏
        WindowCompat.setDecorFitsSystemWindows(window, false)
    }
    
    private fun hideSystemUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 使用WindowInsetsController
            val windowInsetsController = window.insetsController
            windowInsetsController?.apply {
                hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
                systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        } else {
            // Android 11以下使用系统UI可见性标志
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            )
        }
        
        // 使用WindowInsetsControllerCompat作为备用方案
        val windowInsetsController = WindowInsetsControllerCompat(window, window.decorView)
        windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
        windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    }
    
    private fun initViews() {
        imageView = findViewById(R.id.imageView)
        topBar = findViewById(R.id.topBar)
        btnClose = findViewById(R.id.btnClose)
        crosshairVertical = findViewById(R.id.crosshairVertical)
        crosshairHorizontal = findViewById(R.id.crosshairHorizontal)
        clickMarker = findViewById(R.id.clickMarker)
        
        // 创建模式切换按钮
        btnMode = Button(this).apply {
            text = "单点模式"
            setBackgroundColor(Color.argb(180, 0, 0, 0))
            setTextColor(Color.WHITE)
            textSize = 14f
            setPadding(20, 10, 20, 10)
        }
        
        // 将模式按钮添加到topBar
        topBar.addView(btnMode, 0)
        
        // 创建绘制覆盖层
        drawingOverlay = DrawingOverlay(this)
        val rootView = findViewById<ViewGroup>(android.R.id.content)
        rootView.addView(drawingOverlay)
        
        // 创建矩形编辑按钮容器
        createEditButtons(rootView)
    }
    
    /**
     * 创建矩形编辑按钮
     */
    private fun createEditButtons(rootView: ViewGroup) {
        // 创建按钮容器
        editButtonsContainer = LinearLayout(this).apply {
            orientation = LinearLayout.HORIZONTAL
            gravity = android.view.Gravity.CENTER
            setPadding(20, 20, 20, 20)
            setBackgroundColor(Color.argb(180, 0, 0, 0))
            visibility = View.GONE
        }
        
        // 创建确认按钮
        btnConfirmRect = Button(this).apply {
            text = "✅ 确认区域"
            setBackgroundColor(Color.argb(200, 0, 150, 0))
            setTextColor(Color.WHITE)
            textSize = 16f
            setPadding(30, 15, 30, 15)
            
            setOnClickListener {
                confirmRectangleSelection()
            }
        }
        
        // 创建取消按钮
        btnCancelRect = Button(this).apply {
            text = "❌ 重新选择"
            setBackgroundColor(Color.argb(200, 150, 0, 0))
            setTextColor(Color.WHITE)
            textSize = 16f
            setPadding(30, 15, 30, 15)
            
            setOnClickListener {
                cancelRectangleSelection()
            }
        }
        
        // 添加按钮到容器
        val buttonMargin = 20
        val leftParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            setMargins(0, 0, buttonMargin, 0)
        }
        
        editButtonsContainer!!.addView(btnConfirmRect, leftParams)
        editButtonsContainer!!.addView(btnCancelRect)
        
        // 设置容器位置（底部居中）
        val containerParams = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            addRule(RelativeLayout.CENTER_HORIZONTAL)
            setMargins(0, 0, 0, 100)
        }
        
        rootView.addView(editButtonsContainer, containerParams)
    }

    private fun setupListeners() {
        btnClose.setOnClickListener {
            finish()
        }
        
        btnMode.setOnClickListener {
            toggleMode()
        }
        
        // 设置图片拖动选点监听
        imageView.setOnTouchListener { _, event ->
            handleTouchEvent(event)
        }
        
        // 设置整个容器的拖动选点监听（防止点击到边缘）
        findViewById<View>(android.R.id.content).setOnTouchListener { _, event ->
            handleTouchEvent(event)
        }
    }
    
    /**
     * 切换选择模式
     */
    private fun toggleMode() {
        isRectangleMode = !isRectangleMode
        btnMode.text = if (isRectangleMode) "矩形模式" else "单点模式"
        
        // 清除之前的选择
        resetSelection()
        
        Toast.makeText(
            this, 
            if (isRectangleMode) "🔲 矩形区域模式：拖拽选择矩形区域" else "📍 单点模式：拖拽选择单个点",
            Toast.LENGTH_SHORT
        ).show()
    }
    
    /**
     * 重置选择状态
     */
    private fun resetSelection() {
        hasSelected = false
        hasSelectedRectangle = false
        isDragging = false
        isSelectingRectangle = false
        isEditingRectangle = false
        editingHandle = EditHandle.NONE
        hideCrosshair()
        drawingOverlay.clearDrawing()
        drawingOverlay.setEditMode(false)
        editButtonsContainer?.visibility = View.GONE
    }
    
    /**
     * 处理触摸事件，支持单点和矩形两种模式
     */
    private fun handleTouchEvent(event: MotionEvent): Boolean {
        return if (isRectangleMode) {
            handleRectangleSelection(event)
        } else {
            handlePointSelection(event)
        }
    }
    
    /**
     * 处理单点选择
     */
    private fun handlePointSelection(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isDragging = true
                hasSelected = false
                updateCrosshairPosition(event.x, event.y, showMarker = false)
                Log.d(TAG, "开始拖动: (${event.x}, ${event.y})")
                return true
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (isDragging) {
                    updateCrosshairPosition(event.x, event.y, showMarker = false)
                }
                return true
            }
            
            MotionEvent.ACTION_UP -> {
                if (isDragging) {
                    isDragging = false
                    hasSelected = true
                    clickX = event.x.toInt()
                    clickY = event.y.toInt()
                    
                    Log.d(TAG, "选中位置: ($clickX, $clickY)")
                    
                    updateCrosshairPosition(event.x, event.y, showMarker = true)
                    
                    imageView.postDelayed({
                        if (hasSelected) {
                            showParameterDialog()
                        }
                    }, 800)
                }
                return true
            }
            
            MotionEvent.ACTION_CANCEL -> {
                isDragging = false
                hideCrosshair()
                return true
            }
        }
        
        return false
    }
    
    /**
     * 处理矩形区域选择和编辑
     */
    private fun handleRectangleSelection(event: MotionEvent): Boolean {
        if (isEditingRectangle) {
            return handleRectangleEditing(event)
        }
        
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isSelectingRectangle = true
                hasSelectedRectangle = false
                rectangleStartX = event.x
                rectangleStartY = event.y
                rectangleEndX = event.x
                rectangleEndY = event.y
                drawingOverlay.setRectangle(rectangleStartX, rectangleStartY, rectangleEndX, rectangleEndY, false)
                Log.d(TAG, "开始选择矩形: (${event.x}, ${event.y})")
                return true
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (isSelectingRectangle) {
                    rectangleEndX = event.x
                    rectangleEndY = event.y
                    drawingOverlay.setRectangle(rectangleStartX, rectangleStartY, rectangleEndX, rectangleEndY, false)
                }
                return true
            }
            
            MotionEvent.ACTION_UP -> {
                if (isSelectingRectangle) {
                    isSelectingRectangle = false
                    rectangleEndX = event.x
                    rectangleEndY = event.y
                    
                    // 确保矩形有最小尺寸
                    val minSize = 20f
                    if (kotlin.math.abs(rectangleEndX - rectangleStartX) < minSize || 
                        kotlin.math.abs(rectangleEndY - rectangleStartY) < minSize) {
                        Toast.makeText(this, "矩形区域太小，请重新选择", Toast.LENGTH_SHORT).show()
                        drawingOverlay.clearDrawing()
                        return true
                    }
                    
                    // 进入编辑模式
                    enterEditMode()
                }
                return true
            }
            
            MotionEvent.ACTION_CANCEL -> {
                isSelectingRectangle = false
                drawingOverlay.clearDrawing()
                return true
            }
        }
        
        return false
    }
    
    /**
     * 处理矩形编辑
     */
    private fun handleRectangleEditing(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                editingHandle = getEditHandle(event.x, event.y)
                lastTouchX = event.x
                lastTouchY = event.y
                Log.d(TAG, "开始编辑矩形，手柄: $editingHandle")
                return editingHandle != EditHandle.NONE
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (editingHandle != EditHandle.NONE) {
                    updateRectangleByHandle(event.x, event.y)
                    drawingOverlay.setRectangle(rectangleStartX, rectangleStartY, rectangleEndX, rectangleEndY, true)
                }
                return true
            }
            
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                editingHandle = EditHandle.NONE
                return true
            }
        }
        
        return false
    }
    
    /**
     * 进入编辑模式
     */
    private fun enterEditMode() {
        isEditingRectangle = true
        hasSelectedRectangle = true
        
        // 显示编辑按钮
        editButtonsContainer?.visibility = View.VISIBLE
        
        // 更新绘制层显示编辑状态
        drawingOverlay.setRectangle(rectangleStartX, rectangleStartY, rectangleEndX, rectangleEndY, true)
        drawingOverlay.setEditMode(true)
        
        Toast.makeText(this, "🔧 编辑模式：拖拽边框调整大小", Toast.LENGTH_SHORT).show()
    }
    
    /**
     * 确认矩形选择
     */
    private fun confirmRectangleSelection() {
        val left = minOf(rectangleStartX, rectangleEndX).toInt()
        val top = minOf(rectangleStartY, rectangleEndY).toInt()
        val right = maxOf(rectangleStartX, rectangleEndX).toInt()
        val bottom = maxOf(rectangleStartY, rectangleEndY).toInt()
        
        Log.d(TAG, "确认矩形区域: ($left, $top) - ($right, $bottom)")
        
        // 隐藏编辑按钮
        editButtonsContainer?.visibility = View.GONE
        isEditingRectangle = false
        
        // 显示参数对话框
        showRectangleParameterDialog(left, top, right, bottom)
    }
    
    /**
     * 取消矩形选择
     */
    private fun cancelRectangleSelection() {
        // 隐藏编辑按钮
        editButtonsContainer?.visibility = View.GONE
        isEditingRectangle = false
        
        // 清除绘制
        drawingOverlay.clearDrawing()
        drawingOverlay.setEditMode(false)
        
        // 重置状态
        resetSelection()
        
        Toast.makeText(this, "🔲 请重新绘制矩形区域", Toast.LENGTH_SHORT).show()
    }
    
    /**
     * 获取编辑手柄类型
     */
    private fun getEditHandle(x: Float, y: Float): EditHandle {
        val handleSize = 30f // 手柄检测区域大小
        
        val left = minOf(rectangleStartX, rectangleEndX)
        val top = minOf(rectangleStartY, rectangleEndY)
        val right = maxOf(rectangleStartX, rectangleEndX)
        val bottom = maxOf(rectangleStartY, rectangleEndY)
        
        // 检测角落手柄
        if (isInRange(x, left, handleSize) && isInRange(y, top, handleSize)) {
            return EditHandle.TOP_LEFT
        }
        if (isInRange(x, right, handleSize) && isInRange(y, top, handleSize)) {
            return EditHandle.TOP_RIGHT
        }
        if (isInRange(x, left, handleSize) && isInRange(y, bottom, handleSize)) {
            return EditHandle.BOTTOM_LEFT
        }
        if (isInRange(x, right, handleSize) && isInRange(y, bottom, handleSize)) {
            return EditHandle.BOTTOM_RIGHT
        }
        
        // 检测边缘手柄
        if (isInRange(x, left, handleSize) && y > top + handleSize && y < bottom - handleSize) {
            return EditHandle.LEFT_EDGE
        }
        if (isInRange(x, right, handleSize) && y > top + handleSize && y < bottom - handleSize) {
            return EditHandle.RIGHT_EDGE
        }
        if (isInRange(y, top, handleSize) && x > left + handleSize && x < right - handleSize) {
            return EditHandle.TOP_EDGE
        }
        if (isInRange(y, bottom, handleSize) && x > left + handleSize && x < right - handleSize) {
            return EditHandle.BOTTOM_EDGE
        }
        
        // 检测矩形内部（移动整个矩形）
        if (x > left + handleSize && x < right - handleSize && 
            y > top + handleSize && y < bottom - handleSize) {
            return EditHandle.MOVE_RECT
        }
        
        return EditHandle.NONE
    }
    
    /**
     * 检查坐标是否在范围内
     */
    private fun isInRange(value: Float, target: Float, range: Float): Boolean {
        return kotlin.math.abs(value - target) <= range
    }
    
    /**
     * 根据手柄更新矩形
     */
    private fun updateRectangleByHandle(x: Float, y: Float) {
        when (editingHandle) {
            EditHandle.TOP_LEFT -> {
                rectangleStartX = x
                rectangleStartY = y
            }
            EditHandle.TOP_RIGHT -> {
                rectangleEndX = x
                rectangleStartY = y
            }
            EditHandle.BOTTOM_LEFT -> {
                rectangleStartX = x
                rectangleEndY = y
            }
            EditHandle.BOTTOM_RIGHT -> {
                rectangleEndX = x
                rectangleEndY = y
            }
            EditHandle.LEFT_EDGE -> {
                rectangleStartX = x
            }
            EditHandle.RIGHT_EDGE -> {
                rectangleEndX = x
            }
            EditHandle.TOP_EDGE -> {
                rectangleStartY = y
            }
            EditHandle.BOTTOM_EDGE -> {
                rectangleEndY = y
            }
            EditHandle.MOVE_RECT -> {
                // 移动整个矩形
                val deltaX = x - lastTouchX
                val deltaY = y - lastTouchY
                rectangleStartX += deltaX
                rectangleEndX += deltaX
                rectangleStartY += deltaY
                rectangleEndY += deltaY
                lastTouchX = x
                lastTouchY = y
            }
            else -> {}
        }
        
        // 确保矩形不会变得太小
        val minSize = 20f
        if (kotlin.math.abs(rectangleEndX - rectangleStartX) < minSize) {
            if (rectangleEndX > rectangleStartX) {
                rectangleEndX = rectangleStartX + minSize
            } else {
                rectangleStartX = rectangleEndX + minSize
            }
        }
        if (kotlin.math.abs(rectangleEndY - rectangleStartY) < minSize) {
            if (rectangleEndY > rectangleStartY) {
                rectangleEndY = rectangleStartY + minSize
            } else {
                rectangleStartY = rectangleEndY + minSize
            }
        }
    }
    
    /**
     * 更新十字准星和标记位置
     */
    private fun updateCrosshairPosition(x: Float, y: Float, showMarker: Boolean) {
        // 更新垂直辅助线
        val crosshairVParams = crosshairVertical.layoutParams as RelativeLayout.LayoutParams
        crosshairVParams.leftMargin = x.toInt() - 1
        crosshairVertical.layoutParams = crosshairVParams
        crosshairVertical.visibility = View.VISIBLE
        
        // 更新水平辅助线
        val crosshairHParams = crosshairHorizontal.layoutParams as RelativeLayout.LayoutParams
        crosshairHParams.topMargin = y.toInt() - 1
        crosshairHorizontal.layoutParams = crosshairHParams
        crosshairHorizontal.visibility = View.VISIBLE
        
        // 根据需要显示/隐藏选中标记
        if (showMarker) {
            val markerParams = clickMarker.layoutParams as RelativeLayout.LayoutParams
            markerParams.leftMargin = (x - clickMarker.width / 2).toInt()
            markerParams.topMargin = (y - clickMarker.height / 2).toInt()
            clickMarker.layoutParams = markerParams
            clickMarker.visibility = View.VISIBLE
        } else {
            clickMarker.visibility = View.GONE
        }
    }
    
    /**
     * 隐藏十字准星和标记
     */
    private fun hideCrosshair() {
        crosshairVertical.visibility = View.GONE
        crosshairHorizontal.visibility = View.GONE
        clickMarker.visibility = View.GONE
    }
    
    private fun loadImage() {
        val imageUriString = intent.getStringExtra(EXTRA_IMAGE_URI)
        if (imageUriString != null) {
            try {
                val imageUri = Uri.parse(imageUriString)
                imageView.setImageURI(imageUri)
                Log.d(TAG, "加载图片成功: $imageUriString")
            } catch (e: Exception) {
                Log.e(TAG, "加载图片失败", e)
                Toast.makeText(this, "加载图片失败", Toast.LENGTH_SHORT).show()
                finish()
            }
        } else {
            Toast.makeText(this, "未获取到图片", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    private fun showParameterDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_tap_params, null)
        
        val tvClickPosition = dialogView.findViewById<TextView>(R.id.tvClickPosition)
        val etSpaceTime = dialogView.findViewById<EditText>(R.id.etSpaceTime)
        val etDelayTime = dialogView.findViewById<EditText>(R.id.etDelayTime)
        
        // 智能反检测参数
        val etRandomOffset = dialogView.findViewById<EditText>(R.id.etRandomOffset)
        val etIntervalRandom = dialogView.findViewById<EditText>(R.id.etIntervalRandom)
        val cbRandomPause = dialogView.findViewById<CheckBox>(R.id.cbRandomPause)
        
        val btnCancel = dialogView.findViewById<Button>(R.id.btnCancel)
        val btnConfirm = dialogView.findViewById<Button>(R.id.btnConfirm)
        
        // 显示点击坐标
        tvClickPosition.text = "📍 单点模式 - 点击位置: X: $clickX, Y: $clickY"
        
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .setCancelable(false)
            .create()
        
        btnCancel.setOnClickListener {
            dialog.dismiss()
            resetSelection()
        }
        
        btnConfirm.setOnClickListener {
            val spaceTime = etSpaceTime.text.toString().toFloatOrNull()
            val delayTime = etDelayTime.text.toString().toFloatOrNull()
            val randomOffset = etRandomOffset.text.toString().toFloatOrNull()
            val intervalRandom = etIntervalRandom.text.toString().toFloatOrNull()
            
            if (validateParameters(spaceTime, delayTime, randomOffset, intervalRandom)) {
                dialog.dismiss()
                startPointAutoClicking(spaceTime!!, delayTime!!, randomOffset!!, intervalRandom!!, cbRandomPause.isChecked)
            }
        }
        
        dialog.show()
    }
    
    private fun showRectangleParameterDialog(left: Int, top: Int, right: Int, bottom: Int) {
        val dialogView = layoutInflater.inflate(R.layout.dialog_tap_params, null)
        
        val tvClickPosition = dialogView.findViewById<TextView>(R.id.tvClickPosition)
        val etSpaceTime = dialogView.findViewById<EditText>(R.id.etSpaceTime)
        val etDelayTime = dialogView.findViewById<EditText>(R.id.etDelayTime)
        
        // 矩形模式下隐藏传统的随机化参数
        val etRandomOffset = dialogView.findViewById<EditText>(R.id.etRandomOffset)
        val etIntervalRandom = dialogView.findViewById<EditText>(R.id.etIntervalRandom)
        val cbRandomPause = dialogView.findViewById<CheckBox>(R.id.cbRandomPause)
        
        etRandomOffset.visibility = View.GONE
        etIntervalRandom.visibility = View.GONE
        
        val btnCancel = dialogView.findViewById<Button>(R.id.btnCancel)
        val btnConfirm = dialogView.findViewById<Button>(R.id.btnConfirm)
        
        val width = right - left
        val height = bottom - top
        tvClickPosition.text = "🔲 矩形模式 - 区域: ($left, $top) 到 ($right, $bottom)\n尺寸: ${width}x${height}像素"
        
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .setCancelable(false)
            .create()
        
        btnCancel.setOnClickListener {
            dialog.dismiss()
            resetSelection()
        }
        
        btnConfirm.setOnClickListener {
            val spaceTime = etSpaceTime.text.toString().toFloatOrNull()
            val delayTime = etDelayTime.text.toString().toFloatOrNull()
            
            if (spaceTime == null || delayTime == null) {
                Toast.makeText(this, "请输入有效的时间参数", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            if (spaceTime <= 0) {
                Toast.makeText(this, "点击间隔必须大于0", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            if (delayTime < 0) {
                Toast.makeText(this, "延迟时间不能小于0", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            dialog.dismiss()
            startRectangleAutoClicking(left, top, right, bottom, spaceTime, delayTime, cbRandomPause.isChecked)
        }
        
        dialog.show()
    }
    
    private fun validateParameters(spaceTime: Float?, delayTime: Float?, randomOffset: Float?, intervalRandom: Float?): Boolean {
        if (spaceTime == null || delayTime == null) {
            Toast.makeText(this, "请输入有效的时间参数", Toast.LENGTH_SHORT).show()
            return false
        }
        
        if (spaceTime <= 0) {
            Toast.makeText(this, "点击间隔必须大于0", Toast.LENGTH_SHORT).show()
            return false
        }
        
        if (delayTime < 0) {
            Toast.makeText(this, "延迟时间不能小于0", Toast.LENGTH_SHORT).show()
            return false
        }
        
        if (randomOffset == null || intervalRandom == null) {
            Toast.makeText(this, "请输入有效的反检测参数", Toast.LENGTH_SHORT).show()
            return false
        }
        
        if (randomOffset < 0 || intervalRandom < 0) {
            Toast.makeText(this, "反检测参数不能为负数", Toast.LENGTH_SHORT).show()
            return false
        }
        
        return true
    }
    
    private fun startPointAutoClicking(
        spaceTime: Float, 
        delayTime: Float, 
        randomOffset: Float, 
        intervalRandom: Float, 
        enableRandomPauseParam: Boolean
    ) {
        val service = TapAccessibilityService.instance
        if (service == null) {
            Toast.makeText(this, "无障碍服务未连接", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        val config = TapConfig().apply {
            x = clickX
            y = clickY
            setIntervalSeconds(spaceTime)
            setDelaySeconds(delayTime)
            isEnabled = true
            useRectangleMode = false
            
            // 设置智能反检测参数
            randomOffsetRange = randomOffset
            intervalRandomRange = intervalRandom
            enableRandomPause = enableRandomPauseParam
        }
        
        Log.d(TAG, "开始单点智能反检测自动点击: $config")
        
        service.startClickingWithDelay(config)
        
        val resultIntent = Intent().apply {
            putExtra(RESULT_CLICK_POSITION, "📍 单点: ($clickX, $clickY)")
            putExtra(RESULT_SPACE_TIME, spaceTime)
            putExtra(RESULT_DELAY_TIME, delayTime)
        }
        setResult(Activity.RESULT_OK, resultIntent)
        
        Toast.makeText(this, "📍 单点智能防检测点击已启动", Toast.LENGTH_LONG).show()
        finish()
    }
    
    private fun startRectangleAutoClicking(
        left: Int, top: Int, right: Int, bottom: Int,
        spaceTime: Float, 
        delayTime: Float, 
        enableRandomPauseParam: Boolean
    ) {
        val service = TapAccessibilityService.instance
        if (service == null) {
            Toast.makeText(this, "无障碍服务未连接", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        val config = TapConfig().apply {
            x = left
            y = top
            setIntervalSeconds(spaceTime)
            setDelaySeconds(delayTime)
            isEnabled = true
            useRectangleMode = true
            rectLeft = left
            rectTop = top
            rectRight = right
            rectBottom = bottom
            enableRandomPause = enableRandomPauseParam
        }
        
        Log.d(TAG, "开始矩形区域自动点击: $config")
        
        service.startClickingWithDelay(config)
        
        val resultIntent = Intent().apply {
            putExtra(RESULT_CLICK_POSITION, "🔲 矩形: ($left,$top)-($right,$bottom)")
            putExtra(RESULT_SPACE_TIME, spaceTime)
            putExtra(RESULT_DELAY_TIME, delayTime)
        }
        setResult(Activity.RESULT_OK, resultIntent)
        
        Toast.makeText(this, "🔲 矩形区域防检测点击已启动", Toast.LENGTH_LONG).show()
        finish()
    }
    
    /**
     * 自定义绘制覆盖层，用于绘制矩形选择和编辑
     */
    private inner class DrawingOverlay(context: android.content.Context) : View(context) {
        private var drawRectangle = false
        private var isFinalized = false
        private var isEditMode = false
        private var drawRectLeft = 0f
        private var drawRectTop = 0f
        private var drawRectRight = 0f
        private var drawRectBottom = 0f
        
        private val rectanglePaint = Paint().apply {
            color = Color.GREEN
            strokeWidth = 4f
            style = Paint.Style.STROKE
            isAntiAlias = true
        }
        
        private val rectangleFillPaint = Paint().apply {
            color = Color.argb(30, 0, 255, 0)
            style = Paint.Style.FILL
            isAntiAlias = true
        }
        
        private val finalizedPaint = Paint().apply {
            color = Color.BLUE
            strokeWidth = 6f
            style = Paint.Style.STROKE
            isAntiAlias = true
        }
        
        private val finalizedFillPaint = Paint().apply {
            color = Color.argb(40, 0, 0, 255)
            style = Paint.Style.FILL
            isAntiAlias = true
        }
        
        // 编辑手柄画笔
        private val handlePaint = Paint().apply {
            color = Color.WHITE
            strokeWidth = 3f
            style = Paint.Style.FILL
            isAntiAlias = true
        }
        
        private val handleStrokePaint = Paint().apply {
            color = Color.BLUE
            strokeWidth = 2f
            style = Paint.Style.STROKE
            isAntiAlias = true
        }
        
        fun setRectangle(left: Float, top: Float, right: Float, bottom: Float, finalized: Boolean) {
            drawRectLeft = left
            drawRectTop = top
            drawRectRight = right
            drawRectBottom = bottom
            drawRectangle = true
            isFinalized = finalized
            invalidate()
        }
        
        fun setEditMode(editMode: Boolean) {
            isEditMode = editMode
            invalidate()
        }
        
        fun clearDrawing() {
            drawRectangle = false
            isFinalized = false
            isEditMode = false
            invalidate()
        }
        
        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            
            if (drawRectangle) {
                val leftPos = minOf(drawRectLeft, drawRectRight)
                val topPos = minOf(drawRectTop, drawRectBottom)
                val rightPos = maxOf(drawRectLeft, drawRectRight)
                val bottomPos = maxOf(drawRectTop, drawRectBottom)
                
                if (isFinalized) {
                    // 最终确定的矩形用蓝色
                    canvas.drawRect(leftPos, topPos, rightPos, bottomPos, finalizedFillPaint)
                    canvas.drawRect(leftPos, topPos, rightPos, bottomPos, finalizedPaint)
                    
                    // 如果是编辑模式，绘制编辑手柄
                    if (isEditMode) {
                        drawEditHandles(canvas, leftPos, topPos, rightPos, bottomPos)
                    }
                } else {
                    // 选择中的矩形用绿色
                    canvas.drawRect(leftPos, topPos, rightPos, bottomPos, rectangleFillPaint)
                    canvas.drawRect(leftPos, topPos, rightPos, bottomPos, rectanglePaint)
                }
            }
        }
        
        /**
         * 绘制编辑手柄
         */
        private fun drawEditHandles(canvas: Canvas, left: Float, top: Float, right: Float, bottom: Float) {
            val handleSize = 12f
            
            // 绘制角落手柄
            drawHandle(canvas, left, top, handleSize) // 左上角
            drawHandle(canvas, right, top, handleSize) // 右上角
            drawHandle(canvas, left, bottom, handleSize) // 左下角
            drawHandle(canvas, right, bottom, handleSize) // 右下角
            
            // 绘制边缘手柄
            drawHandle(canvas, left, (top + bottom) / 2, handleSize) // 左边缘
            drawHandle(canvas, right, (top + bottom) / 2, handleSize) // 右边缘
            drawHandle(canvas, (left + right) / 2, top, handleSize) // 上边缘
            drawHandle(canvas, (left + right) / 2, bottom, handleSize) // 下边缘
        }
        
        /**
         * 绘制单个手柄
         */
        private fun drawHandle(canvas: Canvas, x: Float, y: Float, size: Float) {
            // 绘制白色填充
            canvas.drawCircle(x, y, size, handlePaint)
            // 绘制蓝色边框
            canvas.drawCircle(x, y, size, handleStrokePaint)
        }
    }
} 